package org.cy.shixun.controller.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.cy.shixun.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

//JWT验证拦截器
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //提交方式：post,get,options
        String method = request.getMethod();
        //放行options提交
        if("options".equalsIgnoreCase(method)) {
            return true;
        }
        //中文乱码处理
        response.setHeader("Content-type","text/html;charset=UTF-8");
        //从请求头中拿到token
        String token = request.getHeader("tk");
        if(token != null && redisUtil.getString(token) != null) {
            //重新刷新一下token的有效期
            redisTemplate.expire(token, 3600, TimeUnit.SECONDS);
            return true;
        }
        log.info("已被拦截器拦截并返回");
        response.getWriter().write("请登录后再访问");
        return false;
    }
}
